package com.jstyle.jclife.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Space;
import android.widget.TextView;

import com.jstyle.countrylibrary.CountryPage;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.NetWork.api.JstyleApi;
import com.jstyle.jclife.R;
import com.jstyle.jclife.model.ActionData;
import com.jstyle.jclife.model.BleData;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SHA1;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.view.EditTextWithDelete;
import com.mob.tools.FakeActivity;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

;


/**
 * 注册
 */
public class SignInFragment extends BaseFragment {

    private static final String TAG = "SignInFragment";


    @BindView(R.id.et_signin_phonenumber)
    EditText etSigninPhonenumber;
    @BindView(R.id.et_signin_Verification_Code)
    EditTextWithDelete etSigninVerificationCode;
    @BindView(R.id.bt_signin_get_Verification_Code)
    Button btSigninGetVerificationCode;
    @BindView(R.id.et_signin_password)
    EditText etSigninPassword;

    @BindView(R.id.bt_signin_signin)
    Button btSigninSignin;

    Observer<NetResultData> observer = new Observer<NetResultData>() {


        @Override
        public void onError(Throwable e) {
            disMissProgressDialog();
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(NetResultData netResultData) {
            disMissProgressDialog();
            int msgCode = netResultData.getMsgCode();
            String msg = NetWorkConast.getResult(msgCode, getContext());
            if (msgCode == NetResultData.Success_Code) {
                msg = getResources().getString(R.string.sign_up_complete);
                finishSignIn();
            } else if (msgCode == NetResultData.Failed_Code) {
                msg = getResources().getString(R.string.sign_up_fail);
            }
            showToast(msg);
        }
    };
    @BindView(R.id.bt_signin_countrycode)
    Button btSigninCountrycode;
    @BindView(R.id.tv_findpsd_title)
    TextView tvFindpsdTitle;
    @BindView(R.id.signin_tips)
    TextView signinTips;
    @BindView(R.id.account_space)
    Space accountSpace;
    @BindView(R.id.ll_input)
    LinearLayout llInput;
    @BindView(R.id.tv_to_register)
    TextView tvToRegister;
    @BindView(R.id.bt_login_wechat)
    ImageView btLoginWechat;
    @BindView(R.id.bt_login_facebook)
    ImageView btLoginFacebook;
    @BindView(R.id.bt_login_twitter)
    ImageView btLoginTwitter;
    @BindView(R.id.view_left)
    Button viewLeft;
    @BindView(R.id.tv_or)
    TextView tvOr;
    @BindView(R.id.view_right)
    Button viewRight;
    @BindView(R.id.rg_account)
    RadioGroup rgAccount;

    private boolean isPhoneAccount = true;

    private void finishSignIn() {
        //unsubscribe();
        String account = etSigninPhonenumber.getText().toString();
        String password = etSigninPassword.getText().toString();
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PHONE, account);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_PSD, password);
        SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_countryCode, countryCode);
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_account_type, isPhoneAccount);
        RxBus rxBus = RxBus.getInstance();
        BleData actionData = new BleData();
        actionData.setAction(ActionData.FinishSignIn);
        rxBus.post(actionData);
        getActivity().finish();
    }

    private Disposable subscription;
    private String countryCode = "001-";
    private String language = "zh";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sign_in, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        tvToRegister.setText(Html.fromHtml(getString(R.string.tologin_link)));
        Locale locale = getResources().getConfiguration().locale;
        language = locale.getLanguage();
        isPhoneAccount = SharedPreferenceUtils.getBoolean(SharedPreferenceUtils.KEY_account_type, true);
        etSigninPhonenumber.setHint(isPhoneAccount ? R.string.login_input_phone : R.string.login_input_email);
        btSigninCountrycode.setVisibility(isPhoneAccount ? View.VISIBLE : View.GONE);
        rgAccount.check(isPhoneAccount?R.id.RadioButton_sign_phone:R.id.RadioButton_sign_email);
        rgAccount.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId){
                    case R.id.RadioButton_sign_phone:
                        isPhoneAccount=true;
                        break;
                    case R.id.RadioButton_sign_email:
                        isPhoneAccount=false;
                        break;
                }
                switchAccountType(isPhoneAccount);
            }
        });
    }


    @OnClick({R.id.tv_to_register, R.id.bt_signin_countrycode, R.id.bt_signin_signin, R.id.bt_signin_get_Verification_Code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_to_register:
                getActivity().finish();
                break;
            case R.id.bt_signin_countrycode:
                getCountryCode();
                break;
            case R.id.bt_signin_get_Verification_Code:
                getVerificationCode();
                break;
            case R.id.bt_signin_signin:
                signIn();
                break;
        }
    }

    private void signIn() {
        if (!NetWorkUtil.isNetworkConnected(getContext())) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etSigninPhonenumber.getText().toString();
        String password = etSigninPassword.getText().toString();
        // String confimPassword = etSigninConfimpassword.getText().toString();
        String verCode = etSigninVerificationCode.getText().toString();
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(account) || TextUtils.isEmpty(verCode)) {
            showToast(getString(R.string.fill_all_info));
            return;
        }
        if (password.length() < 6) {
            showToast(getString(R.string.psd_too_short));
            return;
        }
//        if (!password.equals(confimPassword)) {
//            showToast(getString(R.string.sure_psd_same));
//            return;
//        }
        Map<String, Object> map = new HashMap<>();

        if (isPhoneAccount) {
            map.put(NetWorkConast.KEY_PHONE, countryCode + account);
        } else {
            map.put(NetWorkConast.KEY_userEmail, account);
        }
        map.put(NetWorkConast.KEY_userpwd, SHA1.md5Encoder(password));
        map.put(NetWorkConast.KEY_smsCode, verCode);
        NetWorkUtil.addSHA1(map);
        NetWorkUtil.getInstance().getJstyleApi().register(map).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showProgressDialog(getString(R.string.Signing));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
    }

    private void getVerificationCode() {
        if (!NetWorkUtil.isNetworkConnected(getContext())) {
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etSigninPhonenumber.getText().toString();
        if (TextUtils.isEmpty(account)) {
            showToast(getString(R.string.login_input_phone));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        JstyleApi jstyleApi = NetWorkUtil.getInstance().getJstyleApi();
        Observable<NetResultData> observable;

        if (isPhoneAccount) {
            map.put(NetWorkConast.KEY_PHONE, countryCode + account);
            observable = jstyleApi.getSmsCode(map);
        } else {
            map.put(NetWorkConast.KEY_userEmail, account);
            observable = jstyleApi.getEmailCode(map);
        }
        map.put(NetWorkConast.KEY_reqType, language.equals("zh") ? NetWorkConast.ZC_CN : NetWorkConast.ZC_EN);
        NetWorkUtil.addSHA1(map);


        observable.subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
                                                                  @Override
                                                                  public void accept(Disposable disposable) throws Exception {
                                                                      showProgressDialog(getString(R.string.Get_verification_codeing));
                                                                  }
                                                              }
        ).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<NetResultData>() {

            @Override
            public void onError(Throwable e) {
                disMissProgressDialog();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetResultData netResultData) {
                disMissProgressDialog();
                int msgCode = netResultData.getMsgCode();
                String msg = NetWorkConast.getResult(msgCode, getContext());
                if (msgCode == NetResultData.Success_Code) {
                    startTimer();
                    msg = getString(R.string.Get_verification_code_sucessfule);
                }
                showToast(msg);

            }
        });
        ;
    }


    Disposable disposableCode;

    private void startTimer() {
        btSigninGetVerificationCode.setEnabled(false);
        Observable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {
                disposableCode = d;
            }

            @Override
            public void onNext(Long aLong) {

                btSigninGetVerificationCode.setText(String.format(getResources().getString(R.string.formatsecond), 60 - aLong));
                if (aLong == 59) {
                    btSigninGetVerificationCode.setEnabled(true);
                    btSigninGetVerificationCode.setText(getString(R.string.sign_get_vcode));
                    unsubscribe(disposableCode);
                }

            }
        });
    }

    private void unsubscribe(Disposable subscription) {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }

    private void getCountryCode() {
        CountryPage phone = new CountryPage();
        phone.setCountryId("1");
        phone.showForResult(getActivity(), (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                String currentId = (String) data.get("id");
                String[] res = SMSSDK.getCountry(currentId);
                btSigninCountrycode.setText("+" + res[1]);
                countryCode = "00" + res[1] + "-";
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.i(TAG, "onDestroyView: ");
        unsubscribe(disposableCode);



    }

    @Override
    public void switchAccountType(boolean isPhoneAccount) {
        super.switchAccountType(isPhoneAccount);

        etSigninPassword.setText("");
        etSigninPhonenumber.setText("");
        etSigninPhonenumber.setHint(isPhoneAccount ? R.string.login_input_phone : R.string.login_input_email);
        btSigninCountrycode.setVisibility(isPhoneAccount ? View.VISIBLE : View.GONE);
    }
}
